package com.newer.controller.sys;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.newer.pojo.sys.Organization;
import com.newer.pojo.sys.Role;
import com.newer.pojo.sys.RoleExample;
import com.newer.pojo.sys.User;
import com.newer.pojo.sys.UserRole;
import com.newer.service.sys.iter.UserService;
import com.newer.utils.sys.BootstrapDataTable;
import com.newer.utils.sys.Conditions;
import com.newer.utils.sys.MsgUtil;
import com.newer.utils.sys.SuggestUtil;

/**
 * 用户控制器
 */
@RequestMapping("user")
@Controller
public class UserContorller {

	@Autowired
	private UserService userService;

	/**
	 * 跳转修改密码界面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("updatePwd/{id}")
	public String updatePwd(@PathVariable("id") Integer id, HttpServletRequest request, Model model) {
		model.addAttribute("id", id);
		return "sys/user/user_updatePwd";
	}

	/**
	 * 批量删除
	 * 
	 * @param Ids
	 * @return
	 */
	@RequestMapping("batchdelete/{ids}")
	public @ResponseBody MsgUtil toDeleteIds(@PathVariable("ids") String Ids) {
		try {
			userService.deleteUserByIds(Ids);
			return MsgUtil.result(true, "删除成功！");
		} catch (Exception e) {
			return MsgUtil.result(false, "删除失败！");
		}
	}

	/**
	 * 修改密码
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("updatePassword")
	public @ResponseBody MsgUtil updatePassword(User user, HttpServletRequest request, Model model) {
		System.out.println("----------------" + user.getId());
		String newPassword = request.getParameter("newPassword");// 新密码
		user.setPassword(new Md5Hash(newPassword).toString());
		System.out.println(user);
		try {
			userService.updateByPrimaryKeySelective(user);
			return MsgUtil.result(true, "修改成功！");
		} catch (Exception e) {
			e.printStackTrace();
			return MsgUtil.result(false, "系统繁忙，请稍后重试！");
		}
	}

	/**
	 * 跳转添加用户界面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("add")
	public String add(HttpServletRequest request, Model model) {
		List<Organization> organizations = userService.seleteOrganization(null);
		model.addAttribute("organizations", organizations);
		return "sys/user/user_add";
	}

	/**
	 * 添加用户
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("addUser")
	public @ResponseBody MsgUtil addUser(User user) {
		try {
			userService.add(user);
			return MsgUtil.result(true, "添加成功！");
		} catch (Exception e) {
			e.printStackTrace();
			return MsgUtil.result(false, "添加失败！");
		}
	}

	/**
	 * 根据id查询用户数据，返回编辑页面
	 * 
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("update/{id}")
	public String selectById(@PathVariable("id") Integer id, HttpServletRequest request, Model model) {
		RoleExample example = new RoleExample();
		User user = userService.selectByPrimaryKey(id);
		model.addAttribute("user", user);
		List<Organization> organizations = userService.seleteOrganization(null);
		List<Role> roles = userService.seleteRole(example);
		List<UserRole> userRoles = userService.selectUserRoles(id);
		model.addAttribute("organizations", organizations);
		model.addAttribute("userRoles", userRoles);
		model.addAttribute("roles", roles);
		return "sys/user/user_edit";
	}

	/**
	 * 修改用户
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping("updateUser")
	@ResponseBody
	public MsgUtil update(User user) {
		int i = userService.updateUser(user);
		if (i > 0) {
			return MsgUtil.result(true, "修改成功！");
		}
		return MsgUtil.result(false, "修改失败！");
	}

	/**
	 * 所有的user对象
	 * 
	 * @return
	 */
	@RequestMapping("tableView")
	@ResponseBody
	public BootstrapDataTable list(BootstrapDataTable dataTable, Conditions conditions) {
		BootstrapDataTable table = userService.tableView(dataTable, conditions);
		return table;
	}

	/**
	 * 测试bootstrap-suggest插件
	 * 
	 * @return
	 */
	@RequestMapping("tableView1")
	@ResponseBody
	public SuggestUtil list(Conditions conditions) {
		System.out.println(conditions);
		SuggestUtil suggestUtil = userService.selectSuggest(conditions);
		return suggestUtil;
	}

	/**
	 * 删除用户，实则做更新，假删除
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping("delete")
	@ResponseBody
	public MsgUtil deleteUser(User user) {
		try {
			userService.deleteUser(user);
			return MsgUtil.result(true, "删除成功！");
		} catch (Exception e) {
			e.printStackTrace();
			return MsgUtil.result(false, "删除失败！");
		}
	}

	/**
	 * 检查是否有这个用户名
	 * 
	 * @param roleName
	 * @return
	 */
	@RequestMapping("checkUserName")
	@ResponseBody
	public Map<String, Boolean> checkUserName(String userName) {
		Map<String, Boolean> result = userService.seleclUserByUserName(userName);
		return result;
	}

	/**
	 * 检查是否有这个手机号
	 * 
	 * @param roleName
	 * @return
	 */
	@RequestMapping("checkTelephone")
	@ResponseBody
	public Map<String, Boolean> checkTelephone(String telephone, Integer id) {
		Map<String, Boolean> result = userService.seleclUserByTelephone(telephone, id);
		return result;
	}

	/**
	 * 用户登陆
	 * 
	 * @param username
	 * @param password
	 * @return
	 */
	@RequestMapping("/login")
	@ResponseBody
	public MsgUtil userLogin(String username, String password) {
		// 获得当前的Subject
		org.apache.shiro.subject.Subject currentUser = SecurityUtils.getSubject();
		// 测试当前的用户是否已经被认证。(是否已经登陆)
		// 调用Subject的isAuthenticated
		// 把用户名和密码封装成UserPasswordToken对象
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		try {
			// 执行登陆
			currentUser.login(token);
 			// 登陆成功
			return MsgUtil.result(true, "登陆成功!");
			
		} catch (AuthenticationException e) {
			// 登陆失败
			return MsgUtil.result(false, "账号或密码输入有误!");
		}

	}
	
}
